package com.cmcc.linlaker.ui.query;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.cmcc.linlaker.R;
import com.cmcc.linlaker.http.ApiDefine;
import com.cmcc.linlaker.ui.query.adapter.QueryProjectAdapter;
import com.cmcc.linlaker.ui.query.bean.QueryProjectBean;
import com.cmcc.linlaker.ui.query.fragment.ProjectFragment;
import com.cmcc.linlaker.ui.upload.NewUploadQuestionActivity;
import com.cmcc.linlaker.utils.BarUtils;
import com.cmcc.linlaker.utils.IntentUtils;
import com.cmcc.linlaker.utils.ToastUtils;
import com.cmcc.linlaker.utils.Utils;
import com.cmcc.linlaker.volley.GsonRequestHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProjectListActivity extends AppCompatActivity {
    private double latitude, longitude;

    @Nullable
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_project_select);

        BarUtils.initStatusBar(this);

        initView();
    }

    private RecyclerView recycler_project;
    private QueryProjectAdapter adapter;
    private List<QueryProjectBean.QueryProjectData> itemList = new ArrayList<>();

    private EditText edit_search;
    private RelativeLayout layout_clear;

    private MaterialRefreshLayout refreshLayout;
    private String keyName = "";

    private void initView() {
        latitude = getIntent().getDoubleExtra("latitude", 0);
        longitude = getIntent().getDoubleExtra("longitude", 0);

        text_one_kilo = findViewById(R.id.text_one_kilo);
        text_total = findViewById(R.id.text_total);

        recycler_project = findViewById(R.id.recycler_project);
        setRecyclerView(recycler_project, itemList);

        edit_search = findViewById(R.id.edit_search);
        edit_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //关闭软键盘
                    Utils.hideSoftKeyboard(ProjectListActivity.this, edit_search);
                    keyName = edit_search.getText().toString();

                    reset();
                    return true;
                }
                return false;
            }
        });
        edit_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                keyName = edit_search.getText().toString();
                if (TextUtils.isEmpty(keyName)) {
                    reset();
                }
            }
        });


        layout_clear = findViewById(R.id.layout_clear);
        layout_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edit_search.setText("");
            }
        });

        refreshLayout = findViewById(R.id.refresh);
        refreshLayout.setLoadMore(true);
        refreshLayout.setWaveShow(true);
        refreshLayout.setWaveColor(Color.parseColor("#3eaefc"));

        refreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(final MaterialRefreshLayout materialRefreshLayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        reset();
                    }
                }, 2000);
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                if (isHasLoaded) {
                    ToastUtils.showText(ProjectListActivity.this, "数据已全部加载");
                    refreshLayout.finishRefreshLoadMore();
                } else {
                    getProjectList(keyName, false);
                }
            }
        });

        getProjectList(keyName, true);
    }

    private int pageSize = 20;
    private int pageNum = 1;
    private boolean isHasLoaded = false;

    private void reset() {
        itemList.clear();
        pageNum = 1;
        isHasLoaded = false;
        getProjectList(keyName, false);
    }

    private void setRecyclerView(final RecyclerView recycler_view, final List<QueryProjectBean.QueryProjectData> itemList) {
        recycler_view.setHasFixedSize(true);
        recycler_view.setLayoutManager(new LinearLayoutManager(this));

        recycler_view.setNestedScrollingEnabled(false);
        adapter = new QueryProjectAdapter(this, itemList);
        adapter.setOnItemClickListener(new QueryProjectAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(ProjectListActivity.this, NewUploadQuestionActivity.class);
                intent.putExtra("bean", itemList.get(position));
                setResult(1000, intent);
                finish();
            }
        });
        recycler_view.setAdapter(adapter);
    }

    /**
     * 获取项目列表
     */
    public void getProjectList(String projectName, boolean isShowDialog) {
        GsonRequestHelper helper = new GsonRequestHelper(this);
        Map<String, String> params = new HashMap<>();
        params.put("pageSize", pageSize + "");
        params.put("pageNum", pageNum + "");
        params.put("isAsc", "asc");
//        params.put("latitude", Utils.formatLatLng((float) (latitude / 1E6)));
//        params.put("longitude", Utils.formatLatLng((float) (longitude / 1E6)));
        params.put("latitude", latitude + "");
        params.put("longitude", longitude + "");
        if (!isAll) {
            params.put("distance", "1");
        }
        params.put("type", "android");

        params.put("name", projectName);
        params.put("projectSort", "0");
        params.put("type", "android");

        helper.sendPOSTRequest(ApiDefine.PROJECT_SELECT_LIST, QueryProjectBean.class, params, isShowDialog, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    QueryProjectBean bean = (QueryProjectBean) data;

                    if (bean.code.equals("0")) {
                        List<QueryProjectBean.QueryProjectData> rows = bean.rows;
                        if (rows.size() == pageSize) {
                            itemList.addAll(bean.rows);
                            adapter.notifyDataSetChanged();
                            pageNum++;
                        } else {
                            itemList.addAll(bean.rows);
                            adapter.notifyDataSetChanged();
                            isHasLoaded = true;
                        }
                        refreshLayout.finishRefresh();
                        refreshLayout.finishRefreshLoadMore();
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(ProjectListActivity.this);
                    } else {
                        ToastUtils.showText(ProjectListActivity.this, bean.msg);
                    }
                }
            }
        });
    }

    public void back(View view) {
        finish();
    }

    private boolean isAll = false;

    public void oneKiloClick(View view) {
        if (isAll) {
            text_one_kilo.setBackgroundResource(R.drawable.button_all_round_bg_blue3);
            text_one_kilo.setTextColor(0xffffffff);

            text_total.setBackgroundResource(R.drawable.button_all_round_bg_gray);
            text_total.setTextColor(0xff8B8B8B);
        }
        isAll = !isAll;

        reset();
    }

    public void totalClick(View view) {
        if (!isAll) {
            text_total.setBackgroundResource(R.drawable.button_all_round_bg_blue3);
            text_total.setTextColor(0xffffffff);

            text_one_kilo.setBackgroundResource(R.drawable.button_all_round_bg_gray);
            text_one_kilo.setTextColor(0xff8B8B8B);
        }
        isAll = !isAll;

        reset();
    }

    private TextView text_one_kilo, text_total;
}
